<template>
  <div class="right_height">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">采购合同管理</a>
      </el-breadcrumb-item>
    </el-breadcrumb>
    <PersonMenu></PersonMenu>
  </div>
  <div class="right_body">
    <el-card>
      <div class="flex page-header">
        <el-button type="primary" @click="addCustomerInfo">
          <el-icon>
            <Plus />
          </el-icon>
          <span>新增</span>
        </el-button>
        <el-dialog v-model="customerInfoDialog" title="新增合同信息" @close="closeDialog(ruleFormRef)" width="30%" draggable
          align="center">
          <el-card shadow="never">
            <el-form ref="ruleFormRef" :model="ruleForm" label-position="left" label-width="140px" status-icon>
              <el-form-item label="供应商编号：" prop="supNum" :rules="{
                required: true,
                message: '请输入供应商编号',
                trigger: 'blur'
              }">
                <el-input v-model="ruleForm.supNum" placeholder="请输入供应商编号" />
              </el-form-item>
              <el-form-item label="创建人编号：" prop="userNum" :rules="{
                required: true,
              }">
                <el-input v-model="ruleForm.userNum" disabled />
              </el-form-item>
              <el-form-item label="合同附件名称：" prop="pcContractName" :rules="{
                required: true,
                message: '请输入合同附件名称',
                trigger: 'blur'
              }">
                <el-input v-model="ruleForm.pcContractName" placeholder="请输入合同附件名称" />
              </el-form-item>
            </el-form>
          </el-card>
          <template #footer>
            <el-button @click="closeDialog(ruleFormRef)">取消</el-button>
            <el-button type="primary" @click="confirm(ruleFormRef)">提交</el-button>
          </template>
        </el-dialog>
        <el-button type="danger" @click="handleAllDelete" :disabled="sels.length === 0">批量删除</el-button>
        <el-form :inline="true" :model="tableDataSearch" class="demo-form-inline">
          <el-form-item>
            <el-input placeholder="请输入要查询的内容" v-model.trim="tableDataSearch.value">
              <template #append>
                <el-button :icon="Search" @click="search" />
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <!-- 合同信息列表 -->
      <div class="table">
        <el-table ref="tableRef" :data="tableData" :row-key="getKey" empty-text="暂无数据" class="width" align="center"
          @selection-change="selsChange">
          <el-table-column type="selection" width="30" :reserve-selection="true" />
          <el-table-column label="序号" type="index" :width="150" align="center" :data="tableDataIndex">
            <template #default="scope">
              <span>{{
                  (tableDataIndex.pageNum - 1) * tableDataIndex.pageSize +
                  scope.$index +
                  1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="pcNum" label="采购合同编号" align="center" />
          <el-table-column prop="supName" label="供应商名称" align="center" />
          <el-table-column prop="pcStatus" label="采购合同状态" align="center" :filters="[
            { text: '自由', value: 0 },
            { text: '审核中', value: 1 },
            { text: '生效', value: 2 },
            { text: '失效', value: 3 },
          ]" :filter-method="filterStatus" filter-placement="right-end">
            <template #default="scope">
              <el-tag :type="pcStatusfilters(scope.row.pcStatus)">
                {{ pcStatusfilter(scope.row.pcStatus) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="pcContractName" label="合同附件名称" align="center" />
          <el-table-column prop="updateTime" label="创建时间" sortable align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" :icon="View" @click="handleView(scope.row)">查看</el-button>
              <el-button type="danger" :icon="Delete" @click="handleDelete(scope.row.pcId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog v-model="customerInformations" title="合同信息详情" @close="closeDialog(ruleFormRef)" width="30%" draggable
          align="center">
          <el-card shadow="never">
            <el-form ref="ruleFormRef" :model="ruleForm" label-position="left" label-width="120px" status-icon>
              <el-form-item label="采购合同编号：" prop="pcNum" align="left">
                {{ ruleForm.pcNum }}
              </el-form-item>
              <el-form-item label="供应商名称：" prop="supName" align="left">
                {{ ruleForm.supName }}
              </el-form-item>
              <el-form-item label="创建人：" prop="createrName" align="left">
                {{ ruleForm.createrName }}
              </el-form-item>
              <el-form-item label="审批情况：" align="left">
                <div style="flex-direction: column; align-items: flex-start;">
                  <div class='flex'>
                    <p class="warning" v-if="!sup">（供应商）{{ ruleForm.supName }}
                      未审批</p>
                    <p class="success" v-if="sup">（供应商）{{ ruleForm.supName }} 于 {{
                        ruleForm.apprSupDate
                    }} 审批 <span :class="ruleForm.pcAuditStatus == 10 ? 'danger' : 'success'">
                        {{ ruleForm.apprSupOpinion }}</span></p>
                    <br />
                  </div>
                  <div class='flex'>
                    <p class="warning" v-if="!dep">（采购总监）{{ ruleForm.departmentName }}
                      未审批</p>
                    <p class="success" v-if="dep">（采购总监）{{ ruleForm.departmentName }} 于 {{
                        ruleForm.apprDepartmentDate
                    }} 审批 <span :class="ruleForm.pcAuditStatus == 20 ? 'danger' : 'success'">
                        {{ ruleForm.apprDepartmentOpinion }}</span></p>
                    <br />
                  </div>
                  <div class='flex'>
                    <p class="warning" v-if="!fin">（财务总监）{{ ruleForm.financeName }}
                      未审批</p>
                    <p class="success" v-if="fin">（财务总监）{{ ruleForm.financeName }} 于 {{
                        ruleForm.apprFinanceDate
                    }} 审批 <span :class="ruleForm.pcAuditStatus == 30 ? 'danger' : 'success'">
                        {{ ruleForm.apprFinanceOpinion }}</span></p>
                    <br />
                  </div>
                  <div class='flex'>
                    <p class="warning" v-if="!pre">（总经理）{{ ruleForm.presidentName }}
                      未审批</p>
                    <p class="success" v-if="pre">（总经理）{{ ruleForm.presidentName }} 于 {{
                        ruleForm.apprPresidentDate
                    }} 审批 <span :class="ruleForm.pcAuditStatus == 40 ? 'danger' : 'success'">
                        {{ ruleForm.apprPresidentOpinion }}</span></p>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="采购合同状态：" prop="pcStatus" align="left">
                <el-tag :type="pcStatusfilters(ruleForm.pcStatus)">
                  {{ pcStatusfilter(ruleForm.pcStatus) }}</el-tag>
              </el-form-item>
              <el-form-item label="合同附件名称：" prop="pcContractName" align="left">
                {{ ruleForm.pcContractName }}
              </el-form-item>
              <el-form-item label="合同创建时间：" prop="updateTime" align="left">
                {{ ruleForm.updateTime }}
              </el-form-item>
            </el-form>
          </el-card>
          <template #footer>
            <el-button type="primary" @click="closeDialog(ruleFormRef)">确认</el-button>
          </template>
        </el-dialog>
        <el-pagination v-model:currentPage="config.page" :page-size="config.pageSize" small background
          layout="prev, pager, next" :total="config.total" :current-page="config.page" @current-change="changePage" />
      </div>
    </el-card>
  </div>
</template>
<script setup>
import {
  Search,
  View,
  Delete,
} from "@element-plus/icons-vue";
import PersonMenu from "@/components/PersonMenu.vue";
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import httpHelper from "@/api/httpHelper.js";
import utils from "@/utils/utils.js";
import qs from "qs";

let { proxy } = getCurrentInstance();
const ruleFormRef = ref();
const ruleForm = reactive({
  userId: '', // 创建人ID
  pcId: '', // 采购合同ID
  apprId: '', // 审核表ID
  supID: '', // 供应商ID
  userIdDepartment: '', // 采购总监ID
  createrName: '', // 创建人姓名
  supNum: '', // 供应商编号
  supName: '', // 供应商名称
  apprSupDate: '', // 供应商审批日期
  apprSupOpinion: '', // 供应商审批意见
  userNum: 'yybh_98850_00002',
  pcContractName: '', // 合同附件名称
  pcAuditStatus: '', // 审核状态：0未审核 10供应商审核未通过 11供应商审核通过 20总监审核未通过 21总监审核通过（待财务总监未审核）30财务审核未通过 31财务审核通过（待总经理审核）40总经理审核未通过 41总经理审核通过
  pcNum: '', // 采购合同编号
  pcStatus: '', // 采购合同状态（0：自由，1：审核中，2：生效，3：失效）
  pcAppendices: '', // 合同附件存放路径
  updateTime: '', // 更新时间
  departmentNum: '', // 采购总监编号     
  departmentName: '', // 采购总监姓名     
  apprDepartmentDate: '', // 采购总监审批日期 
  apprDepartmentOpinion: '', // 采购总监审批意见 
  userIdFinance: '', // 财务总监id       
  financeNum: '', // 财务总监编号     
  financeName: '', // 财务总监姓名     
  apprFinanceDate: '', // 财务总监审批日期 
  apprFinanceOpinion: '', // 财务总监审批意见 
  userIdPresident: '', // 总经理id         
  presidentNum: '', // 总经理编号       
  presidentName: '', // 总经理姓名       
  apprPresidentDate: '', // 总经理审批日期   
  apprPresidentOpinion: '', // 总经理审批意见   
});

/* 重置和校验按钮 */
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields();
};
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('正确!');
    } else {
      console.log('信息错误!', fields);
    }
  });
};

/* 筛选 */
const filterStatus = (value, row) => {
  return row.pcStatus === value;
};

const pcStatusOptions = ref([
  { pcStatus: 0, text: '自由', type: '' },
  { pcStatus: 1, text: '审核中', type: 'warning' },
  { pcStatus: 2, text: '生效', type: 'success' },
  { pcStatus: 3, text: '失效', type: 'info' }
]);

const pcStatusfilter = (pcStatus) => {
  const obj = pcStatusOptions.value.find((o) => o.pcStatus === pcStatus);
  return obj ? obj.text : null;
};
const pcStatusfilters = (pcStatus) => {
  const obje = pcStatusOptions.value.find((o) => o.pcStatus === pcStatus);
  return obje ? obje.type : null;
};

/* 存储加载到的采购合同数据 */
const tableData = reactive([]);
const tableDataIndex = ref([]);

/* 分页处理 */
const config = reactive({
  total: 0, // 数据总数
  page: 1, // 默认页码为1
  pageSize: 8, // 默认一页显示8条
});
const changePage = () => {
  loadCustomerInfo(config);
};
onMounted(() => {
  loadCustomerInfo(config);
});

/* 加载采购合同数据 */
const loadCustomerInfo = (config) => {
  let pageNum = config.page;
  let pageSize = config.pageSize;
  utils.showLoading();
  httpHelper.get(
    "/supContract/selectAllInform",
    {
      params: {
        pageNum,
        pageSize,
      },
    },
    (res) => {
      console.log(res);
      utils.hideLoading();
      if (tableData.length <= 0) {
        tableData.push(...res.data.data.pageInfo.list);
        tableDataIndex.value = res.data.data.pageInfo;
      } else {
        let list = res.data.data.pageInfo.list;
        let length = res.data.data.pageInfo.pageSize;
        tableData.splice(0, length, ...list);
        tableDataIndex.value = res.data.data.pageInfo;
      }
      config.total = res.data.data.pageInfo.total;
      config.page = res.data.data.pageInfo.pageNum;
    },
    (error) => {
      console.log('加载采购合同出错了' + error);
      utils.hideLoading();
      utils.showError("不好意思，出错了，请联系管理员!");
    }
  );
};
// 表单跨页
const getKey = (row) => {
  return row.pcId;
};

/* 新增采购合同信息 */
const customerInfoDialog = ref(false);
const addCustomerInfo = () => {
  customerInfoDialog.value = true;
};
// 确认添加
const confirm = (formEl) => {
  let userNum = ruleForm.userNum;
  let pcContractName = ruleForm.pcContractName;
  let supNum = ruleForm.supNum;
  if (
    supNum === '' ||
    pcContractName
  ) {
    submitForm(formEl);
    utils.showError("必填项不能为空，请重试！");
  } else {
    httpHelper.post(
      "/supContract/post",
      qs.stringify({
        userNum,
        pcContractName,
        supNum,
      }),
      (res) => {
        console.log(res);
        if (res.data.result) {
          utils.showSuccess(res.data.message);
          customerInfoDialog.value = false;
        } else {
          utils.showError(res.data.message);
          submitForm(formEl);
        }
        loadCustomerInfo(config);
      },
      (error) => {
        console.log('确认添加出错了' + error);
        utils.hideLoading();
        utils.showError("不好意思，出错了，请联系管理员!");
      }
    );
  }
};
// 查看详情
const sup = ref(false);
const dep = ref(false);
const fin = ref(false);
const pre = ref(false);
const customerInformations = ref(false);
const handleView = (row) => {
  customerInformations.value = true;
  proxy.$nextTick(() => { // 浅拷贝
    Object.assign(ruleForm, row);
  });
  switch (row.pcAuditStatus) {
    case 0:
      sup.value = false;
      dep.value = false;
      fin.value = false;
      pre.value = false;
      break;
    case 10:
    case 11:
      sup.value = true;
      dep.value = false;
      fin.value = false;
      pre.value = false;
      break;
    case 20:
    case 21:
      sup.value = true;
      dep.value = true;
      fin.value = false;
      pre.value = false;
      break;
    case 30:
    case 31:
      sup.value = true;
      dep.value = true;
      fin.value = true;
      pre.value = false;
      break;
    case 40:
    case 41:
      sup.value = true;
      dep.value = true;
      fin.value = true;
      pre.value = true;
      break;
    default:
      break;
  }
};

// 取消、关闭
const closeDialog = (formEl) => {
  customerInfoDialog.value = false;
  customerInformations.value = false;
  resetForm(formEl);
};

/* 查询 */
const tableDataSearch = reactive({
  supName: "",
  pcNum: "",
});
const search = () => {
  utils.showLoading();
  let str = tableDataSearch.value;
  console.log(str);
  let pageNum = config.page;
  let pageSize = config.pageSize;
  httpHelper.get(
    "/supContract/getFuzzy",
    {
      params: {
        str,
        pageNum,
        pageSize,
      }
    },
    (res) => {
      console.log(res);
      utils.hideLoading();
      if (res.data.result === false) {
        utils.showError(res.data.message);
      }
      let list = res.data.data.total.list;
      let length = res.data.data.total.pageSize;
      tableData.splice(0, length, ...list);
      tableDataSearch.value = '';
      config.total = res.data.data.total.total;
      config.page = res.data.data.total.pageNum;
    },
    (error) => {
      console.log('查询出错了' + error);
      utils.hideLoading();
      utils.showError("不好意思，出错了，请联系管理员!");
    }
  );
};

// 采购合同列表的选中
let sels = ref([]);
let arr = reactive([]);
const selsChange = (val) => {
  sels.value = val;
  if (sels.value.length === 0) {
    val.forEach((item) => {
      arr.push(item.pcId);
    });
  } else {
    arr = [];
    val.forEach((item) => {
      arr.push(item.pcId);
    });
  }
};

/* 删除 */
const handleDelete = (row) => {
  let pcId = row;
  // utils.showLoading();
  httpHelper.Delete(
    "/supContract/deleteByMap",
    {
      data: { pcId },
    },
    (res) => {
      console.log(res);
      if (res.data.flag) {
        utils.showSuccess(res.data.message);
      } else {
        utils.showError(res.data.message);
      }
      loadCustomerInfo(config);
    },
    (error) => {
      console.log('删除出错了' + error);
      utils.hideLoading();
      utils.showError("不好意思，出错了，请联系管理员!");
    }
  );
};
// 批量删除
const handleAllDelete = () => {
  let pcIds = arr;
  console.log(pcIds);
  // utils.showLoading();
  httpHelper.Delete(
    "/supContract/deleteBatchIds",
    {
      data: { pcIds },
    },
    (res) => {
      console.log(res);
      if (res.data.flag) {
        utils.showSuccess(res.data.message);
      } else {
        utils.showError(res.data.message);
      }
      loadCustomerInfo(config);
    },
    (error) => {
      console.log('删除出错了' + error);
      utils.hideLoading();
      utils.showError("不好意思，出错了，请联系管理员!");
    }
  );
};
</script>
<style lang="less" scoped>
.right_height {
  background-color: #dee1e6;
  overflow: hidden;
}

.el-breadcrumb {
  height: 50px;
  line-height: 50px;
  padding-left: 20px;
  width: 20%;
  float: left;
}

.page-header {
  .el-button--danger {
    margin-left: 12px !important;
  }

  .demo-form-inline {
    margin-left: 12px;
  }

  .el-form-item {
    margin-right: 10px;
  }
}

.flex {
  display: flex;
}

.width {
  width: 100%;
}

.table {
  width: 100%;
}

.success {
  color: #68c242;
}

.danger {
  color: #f36b6e;
}

.warning {
  color: #e5a145;
}
</style>
